{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Task Decomposition in Prompts Tutorial\n",
    "\n",
    "## Overview\n",
    "\n",
    "This tutorial explores the concept of task decomposition in prompt engineering, focusing on techniques for breaking down complex tasks and chaining subtasks in prompts. These techniques are essential for effectively leveraging large language models to solve multi-step problems and perform complex reasoning tasks.\n",
    "\n",
    "## Motivation\n",
    "\n",
    "As AI language models become more advanced, they are increasingly capable of handling complex tasks. However, these models often perform better when given clear, step-by-step instructions. Task decomposition is a powerful technique that allows us to break down complex problems into smaller, more manageable subtasks. This approach not only improves the model's performance but also enhances the interpretability and reliability of the results.\n",
    "\n",
    "## Key Components\n",
    "\n",
    "1. **Breaking Down Complex Tasks**: Techniques for analyzing and dividing complex problems into simpler subtasks.\n",
    "2. **Chaining Subtasks**: Methods for sequentially connecting multiple subtasks to solve a larger problem.\n",
    "3. **Prompt Design for Subtasks**: Crafting effective prompts for each decomposed subtask.\n",
    "4. **Result Integration**: Combining the outputs from individual subtasks to form a comprehensive solution.\n",
    "\n",
    "## Method Details\n",
    "\n",
    "The tutorial employs a step-by-step approach to demonstrate task decomposition:\n",
    "\n",
    "1. **Problem Analysis**: We start by examining a complex task and identifying its component parts.\n",
    "2. **Subtask Definition**: We define clear, manageable subtasks that collectively address the main problem.\n",
    "3. **Prompt Engineering**: For each subtask, we create targeted prompts that guide the AI model.\n",
    "4. **Sequential Execution**: We implement a chain of prompts, where the output of one subtask feeds into the next.\n",
    "5. **Result Synthesis**: Finally, we combine the outputs from all subtasks to form a comprehensive solution.\n",
    "\n",
    "Throughout the tutorial, we use practical examples to illustrate these concepts, demonstrating how task decomposition can be applied to various domains such as analysis, problem-solving, and creative tasks.\n",
    "\n",
    "## Conclusion\n",
    "\n",
    "By the end of this tutorial, learners will have gained practical skills in:\n",
    "- Analyzing complex tasks and breaking them down into manageable subtasks\n",
    "- Designing effective prompts for each subtask\n",
    "- Chaining prompts to guide an AI model through a multi-step reasoning process\n",
    "- Integrating results from multiple subtasks to solve complex problems\n",
    "\n",
    "These skills will enable more effective use of AI language models for complex problem-solving and enhance the overall quality and reliability of AI-assisted tasks."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "First, let's import the necessary libraries and set up our environment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain.prompts import PromptTemplate\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "# Load environment variables\n",
    "load_dotenv()\n",
    "\n",
    "# Set up OpenAI API key\n",
    "os.environ[\"OPENAI_API_KEY\"] = os.getenv('OPENAI_API_KEY')\n",
    "\n",
    "# Initialize the language model\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "def run_prompt(prompt, **kwargs):\n",
    "    \"\"\"Helper function to run a prompt through the language model.\n",
    "\n",
    "    Args:\n",
    "        prompt (str): The prompt template string.\n",
    "        **kwargs: Keyword arguments to fill the prompt template.\n",
    "\n",
    "    Returns:\n",
    "        str: The model's response.\n",
    "    \"\"\"\n",
    "    prompt_template = PromptTemplate(template=prompt, input_variables=list(kwargs.keys()))\n",
    "    chain = prompt_template | llm\n",
    "    return chain.invoke(kwargs).content"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Breaking Down Complex Tasks\n",
    "\n",
    "Let's start with a complex task and break it down into subtasks. We'll use the example of analyzing a company's financial health."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "### Subtask 1: Assess Profitability\n",
      "**Description:** Evaluate the company's profitability by analyzing key metrics such as profit margins and return on assets (ROA). This will involve calculating the net profit margin (Net Income / Revenue) and ROA (Net Income / Total Assets). The objective is to determine how effectively the company converts revenue into profit and how well it utilizes its assets to generate income. \n",
      "\n",
      "### Subtask 2: Evaluate Liquidity and Solvency\n",
      "**Description:** Analyze the company's liquidity and solvency by calculating the current ratio and debt-to-equity ratio. The current ratio can be derived from the company's cash flow from operations and total liabilities, while the debt-to-equity ratio (Total Liabilities / (Total Assets - Total Liabilities)) will provide insight into the company's financial leverage. This subtask aims to assess the company's ability to meet short-term obligations and understand the level of debt relative to equity.\n",
      "\n",
      "### Subtask 3: Examine Cash Flow Health\n",
      "**Description:** Review the company's cash flow from operations to determine its ability to generate cash from core business activities. This includes analyzing the cash flow margin (Cash Flow from Operations / Revenue) and comparing it to net income to assess the quality of earnings. The goal is to understand how well the company is managing its cash flow and whether it can sustain operations and fund growth without relying heavily on external financing.\n"
     ]
    }
   ],
   "source": [
    "complex_task = \"\"\"\n",
    "Analyze the financial health of a company based on the following data:\n",
    "- Revenue: $10 million\n",
    "- Net Income: $2 million\n",
    "- Total Assets: $15 million\n",
    "- Total Liabilities: $7 million\n",
    "- Cash Flow from Operations: $3 million\n",
    "\"\"\"\n",
    "\n",
    "decomposition_prompt = \"\"\"\n",
    "Break down the task of analyzing a company's financial health into 3 subtasks. For each subtask, provide a brief description of what it should accomplish.\n",
    "\n",
    "Task: {task}\n",
    "\n",
    "Subtasks:\n",
    "1.\n",
    "\"\"\"\n",
    "\n",
    "subtasks = run_prompt(decomposition_prompt, task=complex_task)\n",
    "print(subtasks)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Chaining Subtasks in Prompts\n",
    "\n",
    "Now that we have our subtasks, let's create individual prompts for each and chain them together."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Profitability Analysis:\n",
      " To analyze the company's profitability, we can calculate the profit margin using the provided data. The profit margin is a financial metric that indicates the percentage of revenue that has turned into profit. It is calculated using the following formula:\n",
      "\n",
      "\\[\n",
      "\\text{Profit Margin} = \\left( \\frac{\\text{Net Income}}{\\text{Revenue}} \\right) \\times 100\n",
      "\\]\n",
      "\n",
      "Given the values:\n",
      "- Revenue = $10 million\n",
      "- Net Income = $2 million\n",
      "\n",
      "Now, substituting the values into the formula:\n",
      "\n",
      "\\[\n",
      "\\text{Profit Margin} = \\left( \\frac{2,000,000}{10,000,000} \\right) \\times 100\n",
      "\\]\n",
      "\n",
      "Calculating this gives:\n",
      "\n",
      "\\[\n",
      "\\text{Profit Margin} = \\left( 0.2 \\right) \\times 100 = 20\\%\n",
      "\\]\n",
      "\n",
      "### Analysis of the Company's Profitability\n",
      "\n",
      "A profit margin of 20% indicates that the company retains $0.20 as profit for every dollar of revenue generated. This is generally considered a strong profit margin, suggesting that the company is effectively managing its costs relative to its revenue. \n",
      "\n",
      "Here are some key points to consider regarding the company's profitability based on this profit margin:\n",
      "\n",
      "1. **Operational Efficiency**: A profit margin of 20% suggests that the company may have good control over its operating expenses, which can include costs related to production, marketing, and administration.\n",
      "\n",
      "2. **Industry Comparison**: To further assess profitability, it would be beneficial to compare this profit margin with industry averages. If the industry average is lower, it indicates that the company is performing well compared to its peers.\n",
      "\n",
      "3. **Sustainability**: While a 20% profit margin is strong, it is essential to consider whether this level of profitability is sustainable in the long term. Factors such as competitive pressures, changes in consumer demand, and cost fluctuations can all impact future profitability.\n",
      "\n",
      "4. **Growth Potential**: The company should also evaluate how it can leverage its profitability for growth. This could involve reinvesting profits into new products, market expansion, or improving operational efficiencies.\n",
      "\n",
      "In conclusion, the company's 20% profit margin reflects a solid profitability position, but continuous monitoring and strategic planning will be critical to maintaining and enhancing this performance.\n",
      "\n",
      "Liquidity Analysis:\n",
      " To analyze the company's liquidity, we can start by calculating the current ratio. The current ratio is a financial metric that measures a company's ability to cover its short-term liabilities with its short-term assets. However, since we don't have the specific values for current assets and current liabilities, we can derive some insights from the total assets and total liabilities provided.\n",
      "\n",
      "### Given Data:\n",
      "- Total Assets: $15 million\n",
      "- Total Liabilities: $7 million\n",
      "\n",
      "### Current Ratio Calculation:\n",
      "The current ratio is calculated using the formula: \n",
      "\n",
      "\\[\n",
      "\\text{Current Ratio} = \\frac{\\text{Current Assets}}{\\text{Current Liabilities}}\n",
      "\\]\n",
      "\n",
      "Since we do not have the specific values for current assets or current liabilities, we can instead focus on total assets and total liabilities to get a sense of the company's overall financial health. \n",
      "\n",
      "### Analysis of Liquidity:\n",
      "1. **Debt-to-Asset Ratio**: This can provide insight into the proportion of the company's assets that are financed by liabilities.\n",
      "   \\[\n",
      "   \\text{Debt-to-Asset Ratio} = \\frac{\\text{Total Liabilities}}{\\text{Total Assets}} = \\frac{7 \\text{ million}}{15 \\text{ million}} \\approx 0.467\n",
      "   \\]\n",
      "   This indicates that about 46.7% of the company's assets are financed through debt, which is a reasonable level but suggests that the company does carry some risk associated with its liabilities.\n",
      "\n",
      "2. **Equity Position**: To assess the company's equity position, we can calculate total equity:\n",
      "   \\[\n",
      "   \\text{Total Equity} = \\text{Total Assets} - \\text{Total Liabilities} = 15 \\text{ million} - 7 \\text{ million} = 8 \\text{ million}\n",
      "   \\]\n",
      "   This suggests that the company has a solid equity base of $8 million, which indicates a relatively stable financial position.\n",
      "\n",
      "### Conclusion:\n",
      "While we lack specific current asset and current liability figures to compute the current ratio directly, the company's total assets and liabilities suggest a favorable liquidity position overall. With 46.7% of its assets financed by liabilities and a healthy equity cushion, the company appears to be in a good position to meet its obligations. \n",
      "\n",
      "For a more detailed liquidity analysis, it would be beneficial to obtain the current assets and current liabilities figures to calculate the current ratio directly. However, based on the available data, the company does not seem to be in immediate liquidity distress.\n",
      "\n",
      "Cash Flow Analysis:\n",
      " Based on the provided data, the company has a cash flow from operations of $3 million. Here's a brief analysis of its cash flow health:\n",
      "\n",
      "1. **Positive Cash Flow from Operations**: A cash flow of $3 million indicates that the company is generating sufficient cash from its core business activities. This is a positive sign, as it suggests that the company is able to cover its operating expenses and potentially reinvest in growth opportunities.\n",
      "\n",
      "2. **Sustainability**: If this cash flow figure is consistent over time, it could indicate a healthy and sustainable business model. Consistency in cash flow from operations is essential for long-term stability.\n",
      "\n",
      "3. **Comparison to Cash Needs**: To fully assess the cash flow health, it would be important to compare this figure against the company's cash needs for capital expenditures, debt servicing, and other financial obligations. If the cash flow from operations exceeds these needs, the company may be in a strong position.\n",
      "\n",
      "4. **Operational Efficiency**: A strong operational cash flow can point to effective management and operational efficiency. It might be beneficial to analyze further metrics, such as operating margins and revenue growth, to gain deeper insights into operational performance.\n",
      "\n",
      "5. **Room for Improvement**: If the company has significant investments or is in a growth phase, it may need to evaluate whether $3 million is sufficient to support its strategic goals. Additionally, assessing cash flow trends over multiple periods could provide insights into potential weaknesses or opportunities.\n",
      "\n",
      "In summary, while a $3 million cash flow from operations is a positive indicator, a comprehensive evaluation against the company's financial obligations and historical performance is necessary to fully understand its cash flow health.\n"
     ]
    }
   ],
   "source": [
    "def analyze_profitability(revenue, net_income):\n",
    "    \"\"\"Analyze the company's profitability.\n",
    "\n",
    "    Args:\n",
    "        revenue (float): Company's revenue.\n",
    "        net_income (float): Company's net income.\n",
    "\n",
    "    Returns:\n",
    "        str: Analysis of the company's profitability.\n",
    "    \"\"\"\n",
    "    prompt = \"\"\"\n",
    "    Analyze the company's profitability based on the following data:\n",
    "    - Revenue: ${revenue} million\n",
    "    - Net Income: ${net_income} million\n",
    "\n",
    "    Calculate the profit margin and provide a brief analysis of the company's profitability.\n",
    "    \"\"\"\n",
    "    return run_prompt(prompt, revenue=revenue, net_income=net_income)\n",
    "\n",
    "def analyze_liquidity(total_assets, total_liabilities):\n",
    "    \"\"\"Analyze the company's liquidity.\n",
    "\n",
    "    Args:\n",
    "        total_assets (float): Company's total assets.\n",
    "        total_liabilities (float): Company's total liabilities.\n",
    "\n",
    "    Returns:\n",
    "        str: Analysis of the company's liquidity.\n",
    "    \"\"\"\n",
    "    prompt = \"\"\"\n",
    "    Analyze the company's liquidity based on the following data:\n",
    "    - Total Assets: ${total_assets} million\n",
    "    - Total Liabilities: ${total_liabilities} million\n",
    "\n",
    "    Calculate the current ratio and provide a brief analysis of the company's liquidity.\n",
    "    \"\"\"\n",
    "    return run_prompt(prompt, total_assets=total_assets, total_liabilities=total_liabilities)\n",
    "\n",
    "def analyze_cash_flow(cash_flow):\n",
    "    \"\"\"Analyze the company's cash flow.\n",
    "\n",
    "    Args:\n",
    "        cash_flow (float): Company's cash flow from operations.\n",
    "\n",
    "    Returns:\n",
    "        str: Analysis of the company's cash flow.\n",
    "    \"\"\"\n",
    "    prompt = \"\"\"\n",
    "    Analyze the company's cash flow based on the following data:\n",
    "    - Cash Flow from Operations: ${cash_flow} million\n",
    "\n",
    "    Provide a brief analysis of the company's cash flow health.\n",
    "    \"\"\"\n",
    "    return run_prompt(prompt, cash_flow=cash_flow)\n",
    "\n",
    "# Run the chained subtasks\n",
    "profitability_analysis = analyze_profitability(10, 2)\n",
    "liquidity_analysis = analyze_liquidity(15, 7)\n",
    "cash_flow_analysis = analyze_cash_flow(3)\n",
    "\n",
    "print(\"Profitability Analysis:\\n\", profitability_analysis)\n",
    "print(\"\\nLiquidity Analysis:\\n\", liquidity_analysis)\n",
    "print(\"\\nCash Flow Analysis:\\n\", cash_flow_analysis)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Integrating Results\n",
    "\n",
    "Finally, let's integrate the results from our subtasks to provide an overall analysis of the company's financial health."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overall Financial Health Analysis:\n",
      " ### Overall Assessment of the Company's Financial Health\n",
      "\n",
      "Based on the analyses of profitability, liquidity, and cash flow, here are the key points and an overall evaluation of the company's financial position:\n",
      "\n",
      "#### Profitability Analysis\n",
      "- **Profit Margin**: The company has a profit margin of 20%, indicating that it retains $0.20 as profit for every dollar of revenue. This is generally considered a strong performance.\n",
      "- **Operational Efficiency**: The profit margin suggests effective management of operating expenses, positioning the company favorably within its industry.\n",
      "- **Sustainability Considerations**: While the current margin is robust, ongoing monitoring is necessary to ensure that it remains sustainable amidst market fluctuations and competitive pressures.\n",
      "\n",
      "#### Liquidity Analysis\n",
      "- **Debt-to-Asset Ratio**: At approximately 46.7%, this ratio indicates that nearly half of the company's assets are financed through debt. This level is manageable but does suggest some risk exposure due to reliance on borrowed capital.\n",
      "- **Total Equity**: The company has a solid equity base of $8 million, which provides a cushion against liabilities and enhances financial stability.\n",
      "- **Current Ratio**: While the exact current ratio could not be computed due to a lack of specific current assets and current liabilities data, the overall debt management indicates that the company is not in immediate liquidity distress.\n",
      "\n",
      "#### Cash Flow Analysis\n",
      "- **Cash Flow from Operations**: A positive cash flow of $3 million from operations suggests that the company is generating adequate cash from its core business activities, which is essential for covering operating expenses and potential reinvestment.\n",
      "- **Sustainability and Comparisons**: Consistency in this cash flow figure over time would be crucial for long-term stability. Further analysis against the company's cash needs and historical performance could provide deeper insights.\n",
      "\n",
      "### Overall Evaluation\n",
      "The company presents a **favorable financial position** characterized by strong profitability, manageable liquidity levels, and positive operational cash flow. Here are the overall takeaways:\n",
      "\n",
      "1. **Strengths**: The 20% profit margin reflects effective cost management and operational efficiency. Additionally, a solid equity position indicates a stable financial foundation.\n",
      "  \n",
      "2. **Risks**: The reliance on debt financing (46.7% debt-to-assets) poses some risk, highlighting the importance of effective debt management and monitoring of interest obligations.\n",
      "\n",
      "3. **Opportunities**: The positive cash flow from operations provides the company with the ability to reinvest in growth and respond to market opportunities.\n",
      "\n",
      "4. **Recommendations**: Continuous monitoring of profitability, liquidity ratios, and cash flow trends is essential. Additionally, obtaining detailed current asset and liability data would enhance liquidity analysis and allow for a more comprehensive financial assessment.\n",
      "\n",
      "In conclusion, while the company is currently in a good financial position, ongoing strategic planning and risk management will be vital to sustaining its performance and navigating potential future challenges.\n"
     ]
    }
   ],
   "source": [
    "def integrate_results(profitability, liquidity, cash_flow):\n",
    "    \"\"\"Integrate the results from subtasks to provide an overall analysis.\n",
    "\n",
    "    Args:\n",
    "        profitability (str): Profitability analysis.\n",
    "        liquidity (str): Liquidity analysis.\n",
    "        cash_flow (str): Cash flow analysis.\n",
    "\n",
    "    Returns:\n",
    "        str: Overall analysis of the company's financial health.\n",
    "    \"\"\"\n",
    "    prompt = \"\"\"\n",
    "    Based on the following analyses, provide an overall assessment of the company's financial health:\n",
    "\n",
    "    Profitability Analysis:\n",
    "    {profitability}\n",
    "\n",
    "    Liquidity Analysis:\n",
    "    {liquidity}\n",
    "\n",
    "    Cash Flow Analysis:\n",
    "    {cash_flow}\n",
    "\n",
    "    Summarize the key points and give an overall evaluation of the company's financial position.\n",
    "    \"\"\"\n",
    "    return run_prompt(prompt, profitability=profitability, liquidity=liquidity, cash_flow=cash_flow)\n",
    "\n",
    "overall_analysis = integrate_results(profitability_analysis, liquidity_analysis, cash_flow_analysis)\n",
    "print(\"Overall Financial Health Analysis:\\n\", overall_analysis)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
